<template>
  <div class="income-list-wrap">
    <div class="header-box" style="margin-bottom:10px;">
      <Title title="收入项" />
      <MoreOpeator
        v-if="detailData && detailData.projectStatus <= 1 && (hasRouteAuth('crm:projectInfo:addIncome') || hasRouteAuth('crm:projectInfo:delIncome'))"
        :list="[
          {label: '批量新增', auth: hasRouteAuth('crm:projectInfo:addIncome')},
          {label: '批量编辑', auth: hasRouteAuth('crm:projectInfo:addIncome')},
          {label: '批量删除', auth: hasRouteAuth('crm:projectInfo:delIncome')}
        ]"
        :handel-click="moreOpeatorClick"
        label="批量操作"
        style="margin-right:16px;"
      />
      <PlainCreateBtn
        v-if="hasRouteAuth('crm:projectInfo:addIncome') && detailData && (detailData.projectStatus === 0 || detailData.projectStatus === 1 )"
        @click="addIncomItem">添加</PlainCreateBtn>
    </div>
    <div class="table-list">
      <div v-loading="listLoading">
        <el-table
          v-if="list.length > 0 && incomeAuth"
          :data="list"
          :row-class-name="(data) => tableRowClassName(data)"
          class="fb-table income-list-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @selection-change="handleSelectionChange">
          <el-table-column
            :selectable="selectable"
            align="center"
            type="selection"
            width="50"
          />
          <el-table-column align="left" label="项目类型" width="110">
            <template slot-scope="scope">
              {{ scope.row.projectTypeStr }}
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本项" width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.costItemName" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.costItemName }}</div>
                <div class="ellipsisOne">{{ scope.row.costItemName }}</div>
              </el-tooltip>
              <div v-else class="ellipsisOne">--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="说明" min-width="150">
            <template slot-scope="scope">
              <div v-if="scope.row.isOrderNum" class="ellipsisOne" style="cursor: pointer;" @click="searchOrder(scope.row)">
                订单数量: <span style="color: #406EFF;">{{ scope.row.orderNum }}</span>
              </div>
              <el-tooltip v-else-if="scope.row.explain" placement="top">
                <div slot="content" style="max-width: 200px;">{{ scope.row.explain }}</div>
                <div class="ellipsisOne">
                  {{ scope.row.explain }}
                </div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="right" label="含税金额(元)" width="110">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
            </template>
          </el-table-column>
          <el-table-column align="right" label="含税成本(元)" width="110">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.costAmount" :price="scope.row.costAmount / 100" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="申请人" min-width="110">
            <template slot-scope="scope">
              <CheckUserInfo :label="scope.row.proposer" :user-id="scope.row.proposerId" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="创建人" min-width="110">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creatorId" :label="scope.row.creator" :user-id="scope.row.creatorId" />
              <div v-else>{{ scope.row.creator || '--' }}</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本结算状态" width="110">
            <template slot-scope="scope">
              <div>{{ scope.row.settlementStatus | settlementStatusFilter }}</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="创建时间" min-width="150">
            <template slot-scope="scope">
              <div v-if="scope.row.createDate">{{ scope.row.createDate | standardFormat('YYYY/MM/DD HH:mm') }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column v-if="detailData.projectStatus <= 1" align="left" width="120" label="操作">
            <template slot-scope="scope">
              <div v-if="!(scope.row.projectTypeStr === '外部媒介' || scope.row.projectTypeStr === '内部媒介')" class="flex">
                <el-button :disabled="!hasRouteAuth('crm:projectInfo:addIncome')" style="padding:0;margin:0;" type="text" @click="toEdit(scope)"><span style="font-size:14px;">编辑</span></el-button>
                <el-button :disabled="!hasRouteAuth('crm:projectInfo:delIncome')" class="border-left" type="text" @click="toDeleted(scope)"><span style="font-size:14px;">删除</span></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <empty-placeholder v-else :text="incomeAuth?'暂无数据':'暂无权限'" is-border mode="table" style="margin-bottom: 24px" />
      </div>
    </div>
    <batchCreateDialog ref="batchCreateDialogRef" :project-id="projectId" request-type="income" @freshData="freshData" />
    <create-income-dialog ref="createIncomeDialog" :is-submit="isSubmit" :btn-loading="btnLoading" @addItem="addIncomeItem" @editItem="editIncomeItem" @success="success"/>
  </div>
</template>
<script>
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import Title from '@/components/Title';
import { standardFormat } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
// batchGetIncomeList
import { getIncomeList, deleteIncomeItem, getIncomeItemInfo, batchGetIncomeList,
  addIncomeItem, editIncomeItem, batchDeleteIncome } from '@/api/project';
import CreateIncomeDialog from './model/createIncomeDialog';
import { hasRouteAuth } from '@/utils/permission';
import { settlementStatusFilter } from '@/filters/status';
import { mapState } from 'vuex';
// components
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import batchCreateDialog from './model/batchCreateDialog';

export default {
  name: 'IncomeList',
  filters: {
    standardFormat,
    moneyFilter, settlementStatusFilter
  },
  components: {
    Title,
    EmptyPlaceholder,
    CreateIncomeDialog,
    MoreOpeator, batchCreateDialog
  },
  props: {
    projectId: {
      type: Number,
      default: null
    },
    detailData: {
      type: Object,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      listLoading: false,
      id: '',
      list: [],
      isSubmit: false,
      incomeId: null,
      btnLoading: false,
      multipleSelection: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    incomeAuth() {
      return hasRouteAuth('crm:projectInfo:incomeRead') || hasRouteAuth('crm:projectInfo:incomeAdmin') || this.isAdmin;
    },
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  created() {
    this.id = Number(this.$route.params.id) || '';
    this.fetchData();
  },
  methods: {
    hasRouteAuth,
    addIncomItem() {
      this.$refs.createIncomeDialog.dialogVisible = true;
    },
    toDeleted(scope) {
      const id = scope.row.id;
      this.$confirm('是否确定删除该收入项', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        deleteIncomeItem(id).then(res => {
          this.$message.success('删除成功');
          this.fetchData();
          this.$emit('getDetail');
        }, result => {
          // this.$message.error(result.message);
        }).catch(err => {
          console.error(err);
        });
      });
    },
    toEdit(scope) { // 3.0.2新增申请人
      this.incomeId = scope.row.id;
      getIncomeItemInfo(this.incomeId).then(res => {
        const params = res.data;
        params.costItemId = scope.row.costItemId;
        params.costItemName = scope.row.costItemName;
        if (this.$refs.createIncomeDialog) this.$refs.createIncomeDialog.initInfo(params);
      }).catch(err => {
        console.error(err);
      });
      if (this.$refs.createIncomeDialog) this.$refs.createIncomeDialog.dialogVisible = true;
    },
    searchOrder(item) {
      this.$emit('searchOrder', item.projectType);
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      if (!this.id) return;
      this.listLoading = true;
      getIncomeList(this.id, { notShowNoAuthTip: true }).then(res => {
        this.list = res.data;
        this.ids = '';
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.log(e);
      });
    },
    success() { // 编辑，新建收入项后刷新列表
      this.fetchData();
      this.$emit('getDetail');
    },
    editIncomeItem(param) {
      this.btnLoading = true;
      editIncomeItem(this.incomeId, param).then(res => {
        this.btnLoading = false;
        this.isSubmit = false;
        if (res.code === 200) {
          if (this.$refs.createIncomeDialog) this.$refs.createIncomeDialog.handleSuccess(0);
        }
      }).catch((e) => {
        this.isSubmit = false;
        this.btnLoading = false;
      });
    },
    addIncomeItem(param) {
      this.btnLoading = true;
      addIncomeItem(this.id, param).then(res => {
        this.btnLoading = false;
        this.isSubmit = false;
        if (res.code === 200) {
          if (this.$refs.createIncomeDialog) this.$refs.createIncomeDialog.handleSuccess(1);
        }
      }).catch((e) => {
        this.isSubmit = false;
        this.btnLoading = false;
      });
    },
    handleSelectionChange(value) {
      this.multipleSelection = value;
    },
    /** 批量操作 */
    moreOpeatorClick(i) {
      const costItemArr = {};
      if (i.label === '批量新增') {
        this.$refs.batchCreateDialogRef.openDialog();
      } else if (i.label === '批量编辑') {
        let ids = [];
        if (this.multipleSelection.length <= 0) {
          ids = this.list.map(item => {
            if ((item.id || item.id === 0) && !(item.projectTypeStr === '外部媒介' || item.projectTypeStr === '内部媒介')) {
              costItemArr[item.id] = {
                costItemId: item.costItemId,
                costItemName: item.costItemName
              };
              return item.id;
            }
          }).filter(j => {
            return j || j === 0;
          });
        } else {
          ids = this.multipleSelection.map(item => {
            costItemArr[item.id] = {
              costItemId: item.costItemId,
              costItemName: item.costItemName
            };
            return item.id;
          });
        }
        if (ids.length === 0) {
          this.$message.warning('没有可编辑的项');
          return;
        }
        this.getIncomeList(ids, costItemArr);
      } else if (i.label === '批量删除') {
        this.batchDelete();
      }
    },
    getIncomeList(idsArray, costItemArr) {
      const ids = idsArray.join(',');
      batchGetIncomeList({ ids }).then(res => {
        if (res.code === 200) {
          res.data.forEach(i => {
            i.costItemId = costItemArr[i.id].costItemId;
            i.costItemName = costItemArr[i.id].costItemName;
          });
          this.$refs.batchCreateDialogRef.openDialog(res.data, true, costItemArr);
        }
      });
    },
    batchDelete() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请选择需要删除的项');
        return;
      }
      const ids = this.multipleSelection.map(i => i.id).join(',');
      this.$confirm('是否确定删除这些收入项', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        const data = { ids };
        batchDeleteIncome(data).then(res => {
          this.$message.success('删除成功');
          this.freshData();
        }).catch(err => {
          console.error(err);
        });
      });
    },
    freshData() {
      this.fetchData();
      this.$emit('getDetail');
    },
    selectable(row, event) {
      return !(row.projectTypeStr === '外部媒介' || row.projectTypeStr === '内部媒介');
    },
    tableRowClassName({ row, rowIndex }) {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const ids = this.multipleSelection.map(i => i.id);
        return ids.includes(row['id']) ? `table-selected` : '';
      }
      return '';
    }

  }
};
</script>

<style lang="scss" scoped>
.header-box {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.text-limit {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp:3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}
.flex {
  display: flex;
  align-items: center;
}
.border-left {
  display: block;
  position: relative;
  padding-left:6px;
  margin-left: 4px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
.income-list-table {
  &::v-deep {
    .el-table__header {
      .el-table-column--selection .cell{
        padding-left: 14px;
      }
    }
  }
}
</style>
